﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ausm.ObjectStore.Example
{
    static class CreateDatabase
    {
        const string _createDB =
@"IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = 'ObjectStore')
BEGIN
	CREATE DATABASE ObjectStore
	SELECT 1
END
ELSE
    SELECT 0";
        const string _createTables =
@"CREATE TABLE Person
(
	Id INT NOT NULL IDENTITY(1,1) CONSTRAINT PK_Person PRIMARY KEY,
	Name NVARCHAR(MAX) NOT NULL
)

CREATE TABLE Address
(
	Id INT NOT NULL IDENTITY(1,1) CONSTRAINT PK_Address PRIMARY KEY,
	Person INT NOT NULL CONSTRAINT FK_Address_Person REFERENCES Person(Id),
	Street NVARCHAR(MAX) NOT NULL,
	ZipCode INT NOT NULL,
	City NVARCHAR(MAX) NOT NULL
)";

        public static void GenerateDataBase()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["default"].ConnectionString.Replace("ObjectStore", "master");

            int createDBValue = 0;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(_createDB, connection))
                {
                    object value = command.ExecuteScalar();
                    if (value is int)
                        createDBValue = (int)value;
                }
            }

            if (createDBValue == 0)
                return;

            connectionString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(_createTables, connection))
                {
                    command.ExecuteNonQuery();
                }
            }

        }
    }
}
